

package com.nhc.activity_fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.astrob.model.Msg;
import com.astrob.naviframe.Start;
import com.astrob.nhcmap.R;
import com.astrob.util.SysUtils;
import com.gpx2shp.JniUtils;
import com.nhc.database.dbmodel.WayTrail;
import com.nhc.database.manager.DBDataCenter;
import com.nhc.database.manager.IECenter;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import zuo.biao.library.base.BaseTabActivity;
import zuo.biao.library.interfaces.OnBottomDragListener;
import zuo.biao.library.ui.AlertDialog;
import zuo.biao.library.ui.EditTextInfoActivity;
import zuo.biao.library.ui.EditTextInfoWindow;
import zuo.biao.library.ui.TopMenuWindow;
import zuo.biao.library.util.StringUtil;

/**
 * 使用方法：复制>粘贴>改名>改代码
 */

/**
 * 带标签的Activity示例
 *
 * @use toActivity(DemoTabActivity.createIntent(...));
 */
public class NaviTrackTabActivity extends BaseTabActivity implements OnClickListener, OnBottomDragListener, AlertDialog.OnDialogButtonClickListener {
    private final String TAG = "NaviTrackTabActivity";

    /**
     * 启动这个Activity的Intent
     *
     * @param context
     * @return
     */
    public static Intent createIntent(Context context) {
        return new Intent(context, NaviTrackTabActivity.class);
    }

    //启动方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    @Override
    public Activity getActivity() {
        return this;
    }

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, this);

        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>

    }


    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    private boolean isWayTrailThis = false;//是否为当前航迹
    //示例代码<<<<<<<<
    //示例代码>>>>>>>>
    @Override
    public void initView() {//必须在onCreate方法内调用
        super.initView();

        if (DBDataCenter.getInstance().wayTrailThis != null
                && DBDataCenter.getInstance().wayTrailEdit.getId() == DBDataCenter.getInstance().wayTrailThis.getId()) {
            isWayTrailThis = true;
        }

        if (isWayTrailThis) {
            addTopRightButton(newTopRightImageView(context, R.drawable.btn_menu_selector)).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    toActivity(TopMenuWindow.createIntent(context, getResources().getStringArray(R.array.top_menu_navitracktab2)), REQUEST_TO_TOP_MENU, false);
                }
            });
        } else {
            addTopRightButton(newTopRightImageView(context, R.drawable.btn_menu_selector)).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    toActivity(TopMenuWindow.createIntent(context, getResources().getStringArray(R.array.top_menu_navitracktab)), REQUEST_TO_TOP_MENU, false);
                }
            });
        }
    }


    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    @Override
    public void initData() {//必须在onCreate方法内调用
        super.initData();

        if (DBDataCenter.getInstance().wayTrailEdit == null) {
            finish();
        }
    }

    @Override
    @Nullable
    public String getTitleName() {
        return getString(R.string.navitrack_titlte);
    }

    @Override
    @Nullable
    public String getReturnName() {
        return "";
    }

    @Override
    @Nullable
    public String getForwardName() {
        return "";
    }

    @Override
    protected String[] getTabNames() {
        return getResources().getStringArray(R.array.top_bar_navitracktab);
    }

    NaviTrackInfoFragment anviTrackInfoFragment;
    NaviTrackMapFragment naviTrackMapFragment;
    NaviTrackChatFragment naviTrackChatFragment;

    @Override
    protected Fragment getFragment(int position) {
        //示例代码<<<<<<<<<<<<<<<<<<
        switch (position) {
            default:
            case 0:
                if (anviTrackInfoFragment == null) {
                    anviTrackInfoFragment = NaviTrackInfoFragment.createInstance();
                }
                return anviTrackInfoFragment;
            case 1:
                if (naviTrackMapFragment == null) {
                    naviTrackMapFragment = NaviTrackMapFragment.createInstance();
                    naviTrackMapFragment.setFatherHandler(mHandler);
                    mapHandler = naviTrackMapFragment.getHandler();
                }
                return naviTrackMapFragment;
            case 2:
                if (naviTrackChatFragment == null) {
                    naviTrackChatFragment = NaviTrackChatFragment.createInstance();
                }
                return naviTrackChatFragment;
        }

//        Bundle bundle = fragment.getArguments();
//        if (bundle == null) {
//            bundle = new Bundle();
//        }
//        fragment.setArguments(bundle);
//        //示例代码>>>>>>>>>>>>>>>>>>
//        return fragment;
    }

    Handler mapHandler;


    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    @Override
    public void initEvent() {//必须在onCreate方法内调用
        super.initEvent();
        topTabView.setOnTabSelectedListener(this);//覆盖super.initEvent();内的相同代码
    }

    @Override
    public void onDragBottom(boolean rightToLeft) {
        //示例代码<<<<<<<<<<<<<<<<<<
        if (rightToLeft) {
            return;
        }

        finish();
        //示例代码>>>>>>>>>>>>>>>>>>
    }

    @Override
    public void onTabSelected(TextView tvTab, int position, int id) {
        super.onTabSelected(tvTab, position, id);
    }

    //类相关监听<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


    //类相关监听>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    //系统自带监听方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //类相关监听>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    //系统自带监听>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    private final int REQUEST_TO_TOP_MENU = 30;
    private final int REQUEST_TO_EDIT_TEXT_INFO = 23;
    private final int REQUEST_TO_DOWNLOADMAP = 24;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_TO_DOWNLOADMAP:
                break;
            case REQUEST_TO_EDIT_TEXT_INFO:
                if (data != null) {
                    String name = StringUtil.getTrimedString(
                            data.getStringExtra(EditTextInfoWindow.RESULT_VALUE));
                    DBDataCenter.getInstance().wayTrailEdit.setName(name);
                    showShortToast(getString(R.string.hjmcyxgw) + name);
                }
                break;
            case REQUEST_TO_TOP_MENU:
                if (data != null) {
                    switch (data.getIntExtra(TopMenuWindow.RESULT_POSITION, -1)) {
                        case 0:
                            editName(true);
                            break;
                        case 1:
                            deleteThis();
                            break;
                        case 2:
                            onNavi(false);
                            break;
                        case 3:
                            daochu2shp();
                            break;
                        case 4:
                            onDaochu();
                            break;
                        case 5:
                            onShare();
                            break;
                        case 6:
                            onDownloadMap();
                            break;
                        case 7:
                            onNavi(true);
                            break;
                        default:
                            break;
                    }
                }
                break;
        }
    }

    private void onDaochu() {
        showProgressDialog(R.string.loading);
        runThread(TAG + "daochuData", new Runnable() {
            @Override
            public void run() {
                ArrayList<WayTrail> naviTrackList = new ArrayList<WayTrail>();
                naviTrackList.add(DBDataCenter.getInstance().wayTrailEdit);
                String name = SysUtils.getInstance().getTimeStr(System.currentTimeMillis());
                String suffix = "naviTrack_" + name;
                final String savePath = IECenter.EXDIR_GPX + suffix + ".gpx";
                IECenter.getInstance().export2GPX(suffix, null, null, naviTrackList);
                runUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        showTip(savePath);
                    }
                });
            }
        });
    }

    void showTip(String savePath) {
        new AlertDialog(this, getString(R.string.daochu_cwd), savePath, false, 0, this).show();
    }

    void doShare(String savePath) {
        ArrayList<Uri> files = new ArrayList<Uri>();
        files.add(Uri.fromFile(new File(savePath)));
        Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);//发送多个文件
        intent.setType("*/*");//多个文件格式
        intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, files);//Intent.EXTRA_STREAM同于传输文件流
        startActivity(intent);
    }

    private void onShare() {
        showProgressDialog(R.string.loading);
        runThread(TAG + "daochuData", new Runnable() {
            @Override
            public void run() {
                ArrayList<WayTrail> naviTrackList = new ArrayList<WayTrail>();
                naviTrackList.add(DBDataCenter.getInstance().wayTrailEdit);

                File file1 = new File(IECenter.EXDIR_GPX);
                if (!file1.exists()) {
                    file1.mkdirs();
                }

                SimpleDateFormat formatter = new SimpleDateFormat(
                        "yyyyMMdd_HHmmss");
                Date curDate = new Date(System.currentTimeMillis());
                String suffix = "naviTrack_" + formatter.format(curDate);

                final String savePath = IECenter.EXDIR_GPX + suffix + ".gpx";
                File gpxFile = new File(savePath);
                if (!gpxFile.exists()) {
                    IECenter.getInstance().export2GPX(suffix, null, null, naviTrackList);
                }
                runUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        doShare(savePath);
                    }
                });
            }
        });
    }

    void daochu2shp() {
        showProgressDialog(R.string.loading);
        runThread(TAG + "daochuData", new Runnable() {
            @Override
            public void run() {
                ArrayList<WayTrail> naviTrackList = new ArrayList<WayTrail>();
                naviTrackList.add(DBDataCenter.getInstance().wayTrailEdit);

                File file1 = new File(IECenter.EXDIR_GPX);
                if (!file1.exists()) {
                    file1.mkdirs();
                }

                SimpleDateFormat formatter = new SimpleDateFormat(
                        "yyyyMMdd_HHmmss");
                Date curDate = new Date(System.currentTimeMillis());
                String suffix = "naviTrack_" + formatter.format(curDate);

                final String savePath = IECenter.EXDIR_GPX + suffix + ".gpx";
                File gpxFile = new File(savePath);
                if (!gpxFile.exists()) {
                    IECenter.getInstance().export2GPX(suffix, null, null, naviTrackList);
                }

//                String command = "test -o /sdcard/SHP/test /sdcard/GPX/test.gpx";// test -o SHP保存文件夹 GPX文件PATH
                //导出的SHP路径
                String strSHPRoot = Environment.getExternalStorageDirectory() + "/SHP/";
                if (!SysUtils.getInstance().is240x320) {
                    strSHPRoot = Start.RUNDIR + "/HCMap_EX/SHP/";
                }
                final String strSHPDir = strSHPRoot + suffix + "/";
                File file2 = new File(strSHPDir);
                if (!file2.exists()) {
                    file2.mkdirs();
                }
                String command = "shp -o " + strSHPDir + suffix + " " + savePath;
                final int result = JniUtils.getInstance().receiveCMD(command);

                runUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        if (result == 0) {
                            finishSHPDaochu(strSHPDir);
                        } else {
                            finishSHPDaochu("导出异常, ret=" + result);
                        }
                    }
                });
            }
        });
    }

    private void finishSHPDaochu(String shppath) {
        showShortToast("SHP：" + shppath);
    }


    private void onDownloadMap() {
        toActivity(DownloadMapActivity.createIntent(context, 2), REQUEST_TO_DOWNLOADMAP);
    }

    private void deleteThis() {
        if (isWayTrailThis) {
            new AlertDialog(context, getString(R.string.wxts), getString(R.string.qdqkdqhj), true, 20, this).show();
        } else {
            new AlertDialog(context, "", getString(R.string.qdscchj), true, 17, this).show();
        }

    }

    private void editName(boolean toWindow) {
        String name = DBDataCenter.getInstance().wayTrailEdit.getName();
        if (toWindow) {
            intent = EditTextInfoWindow.createIntent(context, EditTextInfoWindow.TYPE_NICK
                    , getString(R.string.hjmc), StringUtil.getTrimedString(name), getPackageName());
        } else {
            intent = EditTextInfoActivity.createIntent(context, EditTextInfoActivity.TYPE_NICK
                    , getString(R.string.hjmc), StringUtil.getTrimedString(name));
        }

        toActivity(intent, REQUEST_TO_EDIT_TEXT_INFO, !toWindow);
    }

    private void onNavi(boolean isReverse) {

        if (DBDataCenter.getInstance().wayTrailEdit.trackPointList == null
                || DBDataCenter.getInstance().wayTrailEdit.trackPointList.size() < 3) {
            showShortToast(getString(R.string.navitrackmap_navi));
            return;
        }

        DBDataCenter.getInstance().wayTrailEdit.isReverse = isReverse;
        if (DBDataCenter.getInstance().routeNavi != null) {
            new AlertDialog(context, "", getString(R.string.qdzzdqhxdhrhachjdh), true, 11, this).show();
        } else if (DBDataCenter.getInstance().wayTrailNavi != null) {
            new AlertDialog(context, "", getString(R.string.qdzzdqhjdhrhachjdh), true, 11, this).show();
        } else if (Start.getInstance().isHavePath()) {
            new AlertDialog(context, "", getString(R.string.qdzzdqdhrhksxddh), true, 11, this).show();
        } else {
            if (DBDataCenter.getInstance().wayTrailThis != null
                    && DBDataCenter.getInstance().wayTrailEdit.getId() == DBDataCenter.getInstance().wayTrailThis.getId()) {
                //为当前航迹
                //clone一个航迹
                Start.getInstance().MapKit().clearRoute();
                Start.getInstance().MapKit().clearNavStart();
                Start.getInstance().MapKit().mNavDest = null;
                Start.getInstance().setHavePath(false);
                DBDataCenter.getInstance().routeNavi = null;
                DBDataCenter.getInstance().makerNavi = null;

                DBDataCenter.getInstance().wayTrailNavi = new WayTrail();
                DBDataCenter.getInstance().wayTrailNavi.clone(DBDataCenter.getInstance().reUpdateWayTrail(DBDataCenter.getInstance().wayTrailEdit));
            } else {
                DBDataCenter.getInstance().wayTrailNavi = DBDataCenter.getInstance().wayTrailEdit;
            }
            setResult(Msg.NAVI_TO_DEST);
            finish();
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case Msg.NAVITRACK_NAVI:
                    onNavi(false);
                    break;
                case Msg.NAVITRACK_NAVIBACK:
                    onNavi(true);
                    break;
            }
        }
    };

    @Override
    public void onDialogButtonClick(int requestCode, boolean isPositive) {
        if (isPositive == false) {
            return;
        }

        if (requestCode == 11) {
            Start.getInstance().MapKit().clearRoute();
            Start.getInstance().MapKit().clearNavStart();
            Start.getInstance().MapKit().mNavDest = null;
            Start.getInstance().setHavePath(false);
            DBDataCenter.getInstance().routeNavi = null;
            DBDataCenter.getInstance().makerNavi = null;

            DBDataCenter.getInstance().wayTrailNavi = DBDataCenter.getInstance().wayTrailEdit;
            setResult(Msg.NAVI_TO_DEST);
            finish();
        } else if (requestCode == 17) {
            setResult(Msg.DELETE_THIS);
            finish();
        } else if (requestCode == 20) {
            if (DBDataCenter.getInstance().wayTrailThis != null) {
                DBDataCenter.getInstance().wayTrailThis.reset();
                DBDataCenter.getInstance().doDeleteWayTrailTP(DBDataCenter.getInstance().wayTrailThis.getId());
                if (anviTrackInfoFragment != null) {
                    anviTrackInfoFragment.refreshInfo();
                }
                showShortToast(getString(R.string.dqhjyqk));
            }
        }

    }

    //内部类,尽量少用<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (currentPosition == 1) {
            switch (keyCode) {
                default:
                    break;
                case 21://left
                    doKeyLeft();
                    return true;
                case 22://right
                    doKeyRight();
                    return true;
                case 19://up
                    doKeyUp();
                    return true;
                case 20://down
                    doKeyDown();
                    return true;
            }
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            default:
                break;
            case 21://left
                if (currentPosition == 2) {
                    topTabView.selectUI(1);
                    selectFragment(1);
                } else if (currentPosition == 0) {
                    topTabView.selectUI(2);
                    selectFragment(2);
                }
                break;
            case 22://right
                if (currentPosition == 0) {
                    topTabView.selectUI(1);
                    selectFragment(1);
                } else if (currentPosition == 2) {
                    topTabView.selectUI(0);
                    selectFragment(0);
                }
                break;
            case 19://up
            case 20://down
                if (currentPosition == 0) {
                    anviTrackInfoFragment.doKeyUp();
                }
                break;
            case KeyEvent.KEYCODE_MENU:
                toActivity(TopMenuWindow.createIntent(context, getResources().getStringArray(R.array.top_menu_navitracktab)), REQUEST_TO_TOP_MENU, false);
                break;
            case 24://Zoomin
                if (!SysUtils.getInstance().is240x320) {
                    return true;
                }
                if (mapHandler != null) {
                    mapHandler.sendEmptyMessage(Msg.MAPZOOMIN);
                }
                return true;
            case 25://Zoomout
                if (!SysUtils.getInstance().is240x320) {
                    return true;
                }
                if (mapHandler != null) {
                    mapHandler.sendEmptyMessage(Msg.MAPZOOMOUT);
                }
                return true;
        }

        return super.onKeyUp(keyCode, event);
    }

    private void doKeyDown() {
        if (currentPosition == 1) {
            if (mapHandler != null) {
                mapHandler.sendEmptyMessage(Msg.MAPDOWN);
            }
        }
    }

    private void doKeyUp() {
        if (currentPosition == 1) {
            if (mapHandler != null) {
                mapHandler.sendEmptyMessage(Msg.MAPUP);
            }
        }
    }

    private void doKeyRight() {
        if (currentPosition == 1) {
            if (mapHandler != null) {
                mapHandler.sendEmptyMessage(Msg.MAPRIGHT);
            }
        }
    }

    private void doKeyLeft() {
        if (currentPosition == 1) {
            if (mapHandler != null) {
                mapHandler.sendEmptyMessage(Msg.MAPLEFT);
            }
        }
    }

    //内部类,尽量少用>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

}